package com.plugin; /**
 * 服务管理器，负责管理所有可用服务
 */
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceManager {
    private static ServiceManager instance;
    private final PluginManager pluginManager;
    private final Map<Class<?>, Object> activeServices = new ConcurrentHashMap<>();
    private final Map<Class<?>, Object> defaultServices = new ConcurrentHashMap<>();
    
    private ServiceManager(PluginManager pluginManager) {
        this.pluginManager = pluginManager;
        initializeDefaultServices();
        setupPluginListener();
    }
    
    public static synchronized ServiceManager getInstance(PluginManager pluginManager) {
        if (instance == null) {
            instance = new ServiceManager(pluginManager);
        }
        return instance;
    }
    
    /**
     * 初始化默认服务
     */
    private void initializeDefaultServices() {
        defaultServices.put(LogService.class, new DefaultLogService());
    }
    
    /**
     * 设置插件监听器，当插件状态变化时更新服务
     */
    private void setupPluginListener() {
        pluginManager.addPluginListener(new PluginAdapter() {
            @Override
            public void pluginStarted(PluginEvent event) {
                updateServicesFromPlugin(event.getPlugin());
            }
            
            @Override
            public void pluginStopped(PluginEvent event) {
                removeServicesFromPlugin(event.getPlugin());
                // 回退到默认服务
                restoreDefaultServicesIfNeeded();
            }
            
            @Override
            public void pluginUninstalled(PluginEvent event) {
                removeServicesFromPlugin(event.getPlugin());
                // 回退到默认服务
                restoreDefaultServicesIfNeeded();
            }
        });
    }
    
    /**
     * 从插件更新服务
     */
    private void updateServicesFromPlugin(Plugin plugin) {
        if (plugin instanceof ServiceProvider) {
            ServiceProvider provider = (ServiceProvider) plugin;
            Class<?>[] services = provider.getProvidedServices();
            
            for (Class<?> serviceType : services) {
                Object service = provider.getService(serviceType);
                if (serviceType.isInstance(service)) {
                    activeServices.put(serviceType, service);
                    LogService logService = getService(LogService.class);
                    logService.info("服务 " + serviceType.getSimpleName() + 
                                   " 已更新为 " + plugin.getName() + " 提供的版本");
                }
            }
        }
    }
    
    /**
     * 从插件移除服务
     */
    private void removeServicesFromPlugin(Plugin plugin) {
        if (plugin instanceof ServiceProvider) {
            ServiceProvider provider = (ServiceProvider) plugin;
            Class<?>[] services = provider.getProvidedServices();
            
            for (Class<?> serviceType : services) {
                activeServices.remove(serviceType);
            }
        }
    }
    
    /**
     * 如果没有活跃服务，恢复默认服务
     */
    private void restoreDefaultServicesIfNeeded() {
        for (Map.Entry<Class<?>, Object> entry : defaultServices.entrySet()) {
            if (!activeServices.containsKey(entry.getKey())) {
                LogService logService = getService(LogService.class);
                logService.info("服务 " + entry.getKey().getSimpleName() + 
                               " 已恢复为默认版本");
            }
        }
    }
    
    /**
     * 获取指定类型的服务
     */
    @SuppressWarnings("unchecked")
    public <T> T getService(Class<T> serviceType) {
        T service = (T) activeServices.get(serviceType);
        if (service == null) {
            service = (T) defaultServices.get(serviceType);
        }
        return service;
    }
    
    /**
     * 获取当前活跃服务的信息
     */
    public Map<String, String> getActiveServiceInfo() {
        Map<String, String> info = new HashMap<>();
        
        // 检查所有已知服务类型
        Set<Class<?>> allServiceTypes = new HashSet<>(defaultServices.keySet());
        allServiceTypes.addAll(activeServices.keySet());
        
        for (Class<?> serviceType : allServiceTypes) {
            String providerInfo;
            Object service = activeServices.get(serviceType);
            
            if (service != null) {
                // 查找提供此服务的插件
                Plugin providerPlugin = findPluginProvidingService(serviceType);
                providerInfo = providerPlugin != null ? 
                    providerPlugin.getName() + " (v" + providerPlugin.getVersion() + ")" : 
                    "未知提供者";
            } else {
                providerInfo = "默认实现";
            }
            
            info.put(serviceType.getName(), providerInfo);
        }
        
        return info;
    }
    
    /**
     * 查找提供指定服务的插件
     */
    private Plugin findPluginProvidingService(Class<?> serviceType) {
        for (Plugin plugin : pluginManager.getInstalledPlugins()) {
            if (plugin instanceof ServiceProvider) {
                ServiceProvider provider = (ServiceProvider) plugin;
                for (Class<?> providedType : provider.getProvidedServices()) {
                    if (providedType.equals(serviceType)) {
                        return plugin;
                    }
                }
            }
        }
        return null;
    }
}
